#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
主窗口类
"""

import os
import configparser
from PyQt6.QtWidgets import QMainWindow, QVBoxLayout, QWidget, QHBoxLayout, QMessageBox, QTabWidget, QLabel, QSpacerItem, QSizePolicy, QLineEdit, QPushButton
from PyQt6.QtCore import Qt, QTimer
from .components.folder_settings import FolderSettingsWidget
from .components.order_table import OrderTableWidget
from .components.customer_management import CustomerManagementWidget
from .components.task_statistics import TaskStatisticsWidget
from .components.production_management import ProductionManagementWidget
from .styles import load_styles
from .order_parser import OrderParser
from .websocket_client import WebSocketManager


class MainWindow(QMainWindow):
    """主窗口类"""
    
    def __init__(self):
        super().__init__()
        self.setWindowTitle("下单管理")
        self.setGeometry(100, 100, 1500, 800)
        
        # 初始化管理器
        self.order_parser = OrderParser()
        from .websocket_client import get_websocket_manager
        self.websocket_manager = get_websocket_manager()
        
        # 连接状态标志
        self._connection_notified = False
        
        # 服务器连接状态
        self._order_server_status = "未连接"  # 订单服务器状态
        self._task_server_status = "未连接"   # 任务服务器状态
        
        # 告警闪烁定时器
        self.alarm_blink_timer = QTimer()
        self.alarm_blink_timer.timeout.connect(self._blink_alarm)
        self.alarm_visible = True
        self.has_express_pending = False
        
        # 加载样式
        self.setStyleSheet(load_styles())
        
        # 初始化UI
        self.init_ui()
        
        # 连接信号
        self.connect_signals()
        
        # 程序启动时自动连接服务器
        QTimer.singleShot(500, self._auto_connect_on_startup)
        
    def init_ui(self):
        """初始化用户界面"""
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        main_layout.setSpacing(10)
        main_layout.setContentsMargins(10, 10, 10, 10)
        
        # 创建连接状态栏
        self.create_connection_status_bar(main_layout)
        
        # 创建Tab页面组件
        self.tab_widget = QTabWidget()
        main_layout.addWidget(self.tab_widget)
        
        # 创建订单管理页面
        self.order_page = QWidget()
        order_layout = QVBoxLayout(self.order_page)
        order_layout.setSpacing(10)
        order_layout.setContentsMargins(0, 0, 0, 0)
        
        # 创建文件夹设置组件
        self.folder_settings = FolderSettingsWidget()
        order_layout.addWidget(self.folder_settings)
        
        # 创建订单表格组件
        self.order_table = OrderTableWidget(self.folder_settings)
        order_layout.addWidget(self.order_table)
        
        # 设置订单页面布局比例
        order_layout.setStretch(0, 0)  # 文件夹设置固定高度
        order_layout.setStretch(1, 1)  # 订单表格占据剩余空间
        
        # 添加订单管理页面到Tab
        self.tab_widget.addTab(self.order_page, "订单管理")
        
        # 创建客户管理页面（使用单例WebSocket管理器）
        self.customer_management = CustomerManagementWidget()
        
        # 添加客户管理页面到Tab
        self.tab_widget.addTab(self.customer_management, "客户管理")

        # 创建任务统计页面
        self.task_statistics_widget = TaskStatisticsWidget()
        self.tab_widget.addTab(self.task_statistics_widget, "任务统计")
        
        # 创建生产管理页面
        self.production_management = ProductionManagementWidget()
        self.tab_widget.addTab(self.production_management, "生产管理")
        
        # 初始化时同步一次数据
        QTimer.singleShot(1000, self._sync_production_data)
        
        # 延迟连接任务统计信号（确保WebSocket线程已初始化）
        QTimer.singleShot(1500, self._connect_task_statistics_signals)

    
    def create_connection_status_bar(self, parent_layout):
        """创建连接状态栏"""
        # 创建状态栏容器
        status_container = QWidget()
        status_layout = QHBoxLayout(status_container)
        status_layout.setContentsMargins(0, 0, 20, 0)
        status_layout.setSpacing(10)
        
        # 服务器IP输入框
        ip_label = QLabel("服务器IP:")
        ip_label.setStyleSheet("""
            QLabel {
                padding: 0px 5px;
                color: #666;
            }
        """)
        status_layout.addWidget(ip_label)
        
        self.server_ip_input = QLineEdit()
        self.server_ip_input.setPlaceholderText("请输入服务器IP地址 (如: 192.168.1.100)")
        self.server_ip_input.setFixedWidth(120)
        self.server_ip_input.setStyleSheet("""
            QLineEdit {
                padding: 6px 10px;
                border: 1px solid #d0d0d0;
                border-radius: 4px;
                background-color: white;
            }
            QLineEdit:focus {
                border: 1px solid #4CAF50;
            }
        """)
        self.server_ip_input.textChanged.connect(self._on_server_ip_changed)
        status_layout.addWidget(self.server_ip_input)
        
        # 刷新按钮
        self.refresh_btn = QPushButton("刷新")
        self.refresh_btn.setStyleSheet("""
            QPushButton {
                padding: 6px 16px;
                background-color: #2196F3;
                color: white;
                border: none;
                border-radius: 4px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #1976D2;
            }
            QPushButton:pressed {
                background-color: #1565C0;
            }
        """)
        self.refresh_btn.clicked.connect(self.on_refresh_all)
        status_layout.addWidget(self.refresh_btn)
        
        # 添加间距
        status_layout.addSpacing(20)
        
        # 连接状态标签
        self.connection_status_label = QLabel("订单服务器: 未连接 | 任务服务器: 未连接")
        self.connection_status_label.setStyleSheet("""
            QLabel {
                padding: 8px 12px;
                background-color: #f0f0f0;
                border: 1px solid #d0d0d0;
                border-radius: 4px;
                font-weight: bold;
                color: #666;
            }
        """)

        # 告警相关
        self.alarm_status_label = QLabel("")
        self.alarm_status_label.setStyleSheet("""
            QLabel {
                padding: 0px;
                background-color: transparent;
                border: none;
                color: #888;
                font-size: 24px;
            }
        """)
        
        # 添加到布局
        status_layout.addWidget(self.connection_status_label)
        status_layout.addStretch()
        status_layout.addWidget(self.alarm_status_label)
        spacer_width = self.connection_status_label.sizeHint().width()
        spacer = QSpacerItem(spacer_width, 0, QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Minimum)
        status_layout.addItem(spacer)
        status_layout.addStretch()
        
        # 添加到主布局
        parent_layout.addWidget(status_container)
        
        # 加载保存的服务器IP
        self._load_server_ip()
    
    def update_connection_status(self, status_text, color):
        """更新订单服务器连接状态"""
        self._order_server_status = status_text
        self._update_connection_status_display()
    
    def update_task_server_status(self, status_text, color=None):
        """更新任务服务器连接状态"""
        self._task_server_status = status_text
        self._update_connection_status_display()
    
    def _update_connection_status_display(self):
        """更新连接状态显示（组合两个服务器的状态）"""
        # 根据两个服务器的状态确定整体颜色
        order_color = self._get_status_color(self._order_server_status)
        task_color = self._get_status_color(self._task_server_status)
        
        # 如果两个都连接，显示绿色；如果都断开，显示红色；否则显示橙色
        if self._order_server_status == "已连接" and self._task_server_status == "已连接":
            overall_color = "#28a745"
        elif self._order_server_status == "连接断开" and self._task_server_status == "未连接":
            overall_color = "#dc3545"
        else:
            overall_color = "#ffa500"
        
        status_text = f"订单服务器: {self._order_server_status} | 任务服务器: {self._task_server_status}"
        self.connection_status_label.setText(status_text)
        self.connection_status_label.setStyleSheet(f"""
            QLabel {{
                padding: 8px 12px;
                background-color: {overall_color}20;
                border: 1px solid {overall_color};
                border-radius: 4px;
                font-weight: bold;
                color: {overall_color};
            }}
        """)
    
    def _get_status_color(self, status: str) -> str:
        """根据状态文本返回对应的颜色"""
        if status == "已连接":
            return "#28a745"
        elif status in ["连接断开", "未连接", "连接失败"]:
            return "#dc3545"
        elif status == "连接中":
            return "#ffa500"
        else:
            return "#666"
    
    def _connect_task_statistics_signals(self):
        """连接任务统计组件的WebSocket状态信号"""
        if hasattr(self.task_statistics_widget, 'ws_thread') and self.task_statistics_widget.ws_thread:
            # 断开之前的连接（避免重复连接）
            try:
                self.task_statistics_widget.ws_thread.connected.disconnect()
                self.task_statistics_widget.ws_thread.disconnected.disconnect()
                self.task_statistics_widget.ws_thread.error_occurred.disconnect()
            except:
                pass
            
            # 重新连接信号
            self.task_statistics_widget.ws_thread.connected.connect(self._on_task_server_connected)
            self.task_statistics_widget.ws_thread.disconnected.connect(self._on_task_server_disconnected)
            self.task_statistics_widget.ws_thread.error_occurred.connect(self._on_task_server_error)
            
            # 更新当前状态
            if hasattr(self.task_statistics_widget, '_ws_connected'):
                if self.task_statistics_widget._ws_connected:
                    self.update_task_server_status("已连接")
                else:
                    self.update_task_server_status("未连接")
    
    def _on_task_server_connected(self):
        """任务服务器连接成功"""
        self.update_task_server_status("已连接")
    
    def _on_task_server_disconnected(self):
        """任务服务器连接断开"""
        self.update_task_server_status("连接断开")
    
    def _on_task_server_error(self, message: str):
        """任务服务器连接错误"""
        self.update_task_server_status("连接失败")
        
    def connect_signals(self):
        """连接信号"""
        # 文件夹设置信号
        self.folder_settings.add_order_clicked.connect(self.on_add_order)
        self.folder_settings.path_changed.connect(self.on_path_changed)
        
        # 订单表格信号
        self.order_table.data_changed.connect(self.on_order_data_changed)
        
        # 客户管理信号
        self.customer_management.customer_updated.connect(self.on_customer_updated)
        
        # 任务统计信号
        self.task_statistics_widget.data_updated.connect(self.on_task_statistics_updated)
        
        # 连接任务统计组件的WebSocket状态信号
        self._connect_task_statistics_signals()
        
        # 生产管理信号
        self.production_management.status_update_requested.connect(self.on_production_status_update)
        
        # 订单解析器信号
        self.order_parser.orders_parsed.connect(self.on_orders_parsed)
        self.order_parser.parse_error.connect(self.on_parse_error)
        
        # 连接WebSocket信号
        self.connect_websocket_signals()
    
    def connect_websocket_signals(self):
        """连接WebSocket信号"""
        # WebSocket信号
        self.websocket_manager.connected.connect(self.on_websocket_connected)
        self.websocket_manager.disconnected.connect(self.on_websocket_disconnected)
        self.websocket_manager.orders_received.connect(self.on_orders_received)
        self.websocket_manager.order_created.connect(self.on_order_created)
        self.websocket_manager.order_updated.connect(self.on_order_updated)
        self.websocket_manager.order_deleted.connect(self.on_order_deleted)
        self.websocket_manager.order_status_changed.connect(self.on_order_status_changed)
        self.websocket_manager.monitoring_started.connect(self.on_monitoring_started)
        self.websocket_manager.monitoring_stopped.connect(self.on_monitoring_stopped)
        self.websocket_manager.error_occurred.connect(self.on_websocket_error)
        
        # 连接客户管理的WebSocket消息处理
        self.websocket_manager.message_received.connect(self.on_websocket_message)
        
    def disconnect_websocket_signals(self):
        """断开WebSocket信号"""
        self.websocket_manager.connected.disconnect()
        self.websocket_manager.disconnected.disconnect()
        self.websocket_manager.orders_received.disconnect()
        self.websocket_manager.order_created.disconnect()
        self.websocket_manager.order_updated.disconnect()
        self.websocket_manager.order_deleted.disconnect()
        self.websocket_manager.order_status_changed.disconnect()
        self.websocket_manager.monitoring_started.disconnect()
        self.websocket_manager.monitoring_stopped.disconnect()
        self.websocket_manager.error_occurred.disconnect()
        self.websocket_manager.message_received.disconnect()
        
    def _load_server_ip(self):
        """加载保存的服务器IP"""
        try:
            config_file = "settings.ini"
            if not os.path.exists(config_file):
                return
            
            config = configparser.ConfigParser()
            config.read(config_file, encoding='utf-8')
            
            if config.has_option('Settings', 'server_ip'):
                server_ip = config.get('Settings', 'server_ip')
                if server_ip:
                    self.server_ip_input.setText(server_ip)
                    print(f"📝 已加载服务器IP: {server_ip}")
        except Exception as e:
            print(f"❌ 加载服务器IP失败: {e}")
    
    def _save_server_ip(self, ip: str):
        """保存服务器IP到配置文件"""
        try:
            config_file = "settings.ini"
            config = configparser.ConfigParser()
            
            if os.path.exists(config_file):
                config.read(config_file, encoding='utf-8')
            
            if not config.has_section('Settings'):
                config.add_section('Settings')
            
            config.set('Settings', 'server_ip', ip.strip())
            
            with open(config_file, 'w', encoding='utf-8') as f:
                config.write(f)
            
            print(f"💾 已保存服务器IP: {ip}")
        except Exception as e:
            print(f"❌ 保存服务器IP失败: {e}")
    
    def _on_server_ip_changed(self):
        """服务器IP变化处理"""
        # 可以在这里添加自动保存逻辑
        pass
    
    def _auto_connect_on_startup(self):
        """程序启动时自动连接服务器"""
        ip_address = self.server_ip_input.text().strip()
        if ip_address:
            print("🚀 程序启动，自动连接服务器...")
            self._connect_to_server(ip_address, auto_connect=True)
        else:
            print("ℹ️ 未配置服务器IP，跳过自动连接")
        
        # 通知任务统计组件更新URL（无论是否有IP）
        if hasattr(self, 'task_statistics_widget'):
            self.task_statistics_widget._update_ws_url_from_config()
    
    def on_refresh_all(self):
        """刷新所有页面"""
        ip_address = self.server_ip_input.text().strip()
        shared_folder = self.folder_settings.path_input.text().strip()
        
        if not ip_address:
            QMessageBox.warning(self, "输入错误", "请输入服务器IP地址")
            return
        
        if not shared_folder:
            QMessageBox.warning(self, "输入错误", "请输入共享文件夹名")
            return
        
        print("🔄 刷新所有页面...")
        
        # 刷新连接
        self._connect_to_server(ip_address, auto_connect=False)
        
        # 刷新任务统计页面
        if hasattr(self, 'task_statistics_widget'):
            self.task_statistics_widget.trigger_manual_refresh()
            print("✅ 已刷新任务统计页面")
        
        # 刷新订单表格（通过WebSocket重新获取数据）
        if hasattr(self, 'order_table'):
            # 订单表格的数据会通过WebSocket自动更新，这里可以触发一次手动刷新
            if hasattr(self.order_table, 'refresh_data'):
                self.order_table.refresh_data()
                print("✅ 已刷新订单表格")
        
        # 刷新客户管理页面
        if hasattr(self, 'customer_management'):
            if hasattr(self.customer_management, 'refresh_data'):
                self.customer_management.refresh_data()
                print("✅ 已刷新客户管理页面")
        
        # 刷新生产管理页面（通过同步任务统计数据）
        if hasattr(self, 'production_management'):
            self._sync_production_data()
            print("✅ 已刷新生产管理页面")
    
    def _connect_to_server(self, ip_address: str, auto_connect: bool = False):
        """连接到服务器"""
        shared_folder = self.folder_settings.path_input.text().strip()
        
        # 构建WebSocket URL
        if ip_address.startswith("ws://") or ip_address.startswith("wss://"):
            # 如果已经包含协议，直接使用
            websocket_url = ip_address
        else:
            # 如果没有协议，添加ws://协议和默认端口8000
            websocket_url = f"ws://{ip_address}:8000/ws"
        
        print(f"🔗 尝试连接到: {websocket_url}")
        if shared_folder:
            print(f"📁 共享文件夹: {shared_folder}")
        
        # 保存服务器IP
        self._save_server_ip(ip_address)
        
        # 如果已经连接，先断开
        if self.websocket_manager.is_connected():
            self.websocket_manager.stop()
        
        # 更新WebSocket管理器的URL（单例模式会自动处理URL更新）
        self.websocket_manager = WebSocketManager(websocket_url)

        # 断开WebSocket信号
        self.disconnect_websocket_signals()
        
        # 重新连接信号
        self.connect_websocket_signals()
        
        # 更新连接状态为连接中
        self.update_connection_status("连接中", "#ffa500")
        
        # 启动连接
        self.websocket_manager.start()
        
        # 通知任务统计组件更新URL并重新连接
        if hasattr(self, 'task_statistics_widget'):
            self.task_statistics_widget._update_ws_url_from_config()
            
    def on_add_order(self, order_data):
        """添加订单处理"""
        try:
            # 通过WebSocket发送到服务端
            self.websocket_manager.create_order(order_data)
            QMessageBox.information(self, "添加订单", f"正在添加订单: {order_data.get('number', '')} - {order_data.get('customer', '')}")
        except Exception as e:
            QMessageBox.critical(self, "添加订单失败", f"添加订单时发生错误: {str(e)}")
    
    def on_websocket_connected(self):
        """WebSocket连接成功"""
        print("WebSocket连接成功")
        
        # 更新连接状态为已连接
        self.update_connection_status("已连接", "#28a745")
        
        # 服务端会自动发送订单数据，但需要主动请求客户数据
        # self.websocket_manager.get_orders()
        
        # 主动请求客户数据
        self.websocket_manager.send_message({
            'type': 'get_customers',
            'data': {}
        })
        print("📋 已请求客户数据")
    
    def on_websocket_disconnected(self):
        """WebSocket连接断开"""
        print("WebSocket连接断开")
        
        # 更新连接状态为断开
        self.update_connection_status("连接断开", "#dc3545")
    
    def on_orders_received(self, orders):
        """收到订单数据"""
        print(f"📋 主窗口收到订单数据: {len(orders)} 个订单")
        for i, order in enumerate(orders[:3]):  # 只显示前3个
            print(f"  {i+1}. ID: {order.get('id', 'N/A')}, 编号: {order.get('number', '')}, 客户: {order.get('customer', '')}")
        if len(orders) > 3:
            print(f"  ... 还有 {len(orders) - 3} 个订单")
        
        # 更新表格数据
        self.order_table.update_orders_data(orders)
        print(f"✅ 表格数据已更新")
        
        # 将现有订单数据传递给FolderSettingsWidget，用于重复检查
        self.folder_settings.set_existing_orders(orders)
        
        # 检查是否需要显示快递客户挂版告警
        self._check_express_pending_alarm()
    
    def _update_folder_settings_orders(self):
        """更新FolderSettingsWidget中的现有订单数据"""
        if hasattr(self.order_table, 'orders_data'):
            self.folder_settings.set_existing_orders(self.order_table.orders_data)
    
    def on_order_created(self, order):
        """订单已创建"""
        print(f"订单已创建: {order.get('number', '')} - {order.get('customer', '')}")
        # 添加到表格
        self.order_table.add_new_order(order)
        # 更新FolderSettingsWidget中的现有订单数据
        self._update_folder_settings_orders()
        # 检查是否需要显示快递客户挂版告警
        self._check_express_pending_alarm()
    
    def on_order_updated(self, order):
        """订单已更新"""
        print(f"🔄 主窗口收到订单更新: 编号 {order.get('number', '')} - {order.get('customer', '')}")
        
        # 更新表格中的订单
        order_number = order.get('number', '')
        if order_number:
            # 使用订单编号更新表格
            success = self.order_table.update_order_by_number(order_number, order)
            if success:
                print(f"✅ 已更新表格中的订单: 编号 {order_number}")
            else:
                print(f"⚠️ 未找到订单进行更新: 编号 {order_number}")
                # 如果没找到，请求重新获取所有订单
                print("🔄 请求重新获取所有订单...")
                self.websocket_manager.get_orders()
        else:
            print(f"⚠️ 订单更新消息缺少编号: {order}")
        
        # 检查是否需要显示快递客户挂版告警
        self._check_express_pending_alarm()
    
    def on_order_deleted(self, order_number):
        """订单已删除"""
        print(f"🗑️ 主窗口收到订单删除: 编号 {order_number}")
        
        # 从表格中删除订单（通过编号）
        success = self.order_table.remove_order_by_number(order_number)
        if success:
            print(f"✅ 已从表格删除订单: 编号 {order_number}")
        else:
            print(f"❌ 从表格删除订单失败: 编号 {order_number}")
            print(f"🔄 尝试从服务器获取完整订单数据...")
            # 如果找不到订单，请求服务器发送完整数据
            self.websocket_manager.get_orders()
    
    def on_order_status_changed(self, data):
        """订单状态变化"""
        order_number = data.get('order_number')
        status = data.get('status', {})
        print(f"🔄 主窗口收到状态变化: 编号 {order_number}")
        print(f"📊 状态详情: {status}")
        
        # 更新表格中的订单状态
        if order_number and status:
            success = self.order_table.update_order_status_by_number(order_number, status)
            if success:
                print(f"✅ 表格已更新: 订单编号 {order_number}")
            else:
                print(f"❌ 表格更新失败: 订单编号 {order_number}")
                print(f"🔄 尝试从服务器获取完整订单数据...")
                # 如果找不到订单，请求服务器发送完整数据
                self.websocket_manager.get_orders()
        else:
            print(f"⚠️ 状态数据不完整: order_number={order_number}, status={status}")
        
        # 检查是否需要显示快递客户挂版告警
        self._check_express_pending_alarm()
    
    def on_monitoring_started(self, base_path, date):
        """监控已开始"""
        print(f"监控已开始: {base_path}/{date}")
        QMessageBox.information(self, "监控开始", f"服务端已开始监控: {base_path}/{date}")
    
    def on_monitoring_stopped(self):
        """监控已停止"""
        print("监控已停止")
        QMessageBox.information(self, "监控停止", "服务端已停止监控")
    
    def on_websocket_error(self, error_msg):
        """WebSocket错误"""
        print(f"WebSocket错误: {error_msg}")
        
        # 更新连接状态为错误
        self.update_connection_status("连接失败", "#dc3545")
        
    def _auto_parse_orders(self):
        """自动解析订单"""
        path = self.folder_settings.get_path()
        date = self.folder_settings.get_date()
        
        if not path or not date:
            print("路径或日期为空，跳过解析")
            return
            
        # 设置解析器路径
        self.order_parser.set_base_path(path, date)
        
        # 开始解析
        full_path = self.folder_settings.get_full_path()
        print(f"开始自动解析订单: {full_path}")
        
        if full_path and os.path.exists(full_path):
            orders = self.order_parser.parse_orders_from_folder(full_path)
            if orders:
                print(f"自动解析完成: 找到 {len(orders)} 个订单")
            else:
                print("未找到有效的订单信息")
        else:
            print(f"路径不存在: {full_path}")
            
    def on_path_changed(self, path, date):
        """路径变化处理 - 共享目录变化后立即更新相关内容"""
        shared_folder = date.strip() if date else ""
        
        if not shared_folder:
            return
        
        print(f"📁 共享目录已变化: {shared_folder}")
        
        # 1. 更新订单解析器的路径
        ip_address = self.server_ip_input.text().strip()
        if ip_address:
            # 构建完整路径用于解析器
            full_path = f"\\\\{ip_address}\\{shared_folder}"
            self.order_parser.set_base_path(ip_address, shared_folder)
            print(f"✅ 已更新订单解析器路径: {full_path}")
        
        # 2. 如果已连接服务器，重新启动监控
        if self.websocket_manager.is_connected() and ip_address:
            print(f"🔄 重新启动服务端监控: {ip_address}\\{shared_folder}")
            # 获取当前日期用于监控
            from datetime import datetime
            today = datetime.now()
            date_str = f"{today.month}.{today.day}"
            
            # 发送监控启动请求
            self.websocket_manager.start_monitoring(
                base_path=f"\\\\{ip_address}\\{shared_folder}",
                date=date_str
            )
        
        # 3. 重新获取订单数据（通过WebSocket）
        if self.websocket_manager.is_connected():
            print("🔄 重新获取订单数据...")
            self.websocket_manager.get_orders()
        
        # 4. 刷新订单表格（如果数据已更新）
        # 订单表格会通过WebSocket的orders_received信号自动更新
            
    def on_orders_parsed(self, orders):
        """订单解析完成处理"""
        if orders:
            # 更新订单表格
            self.order_table.update_orders_from_parser(orders)
            
    def on_parse_error(self, error):
        """解析错误处理"""
        QMessageBox.warning(self, "解析错误", error)
    
    def on_order_data_changed(self, order_data):
        """订单数据变化处理"""
        try:
            # 通过WebSocket发送更新到服务端
            if self.websocket_manager and self.websocket_manager.is_connected():
                self.websocket_manager.send_message({
                    'type': 'update_order',
                    'data': order_data
                })
                print(f"已发送订单更新到服务端: {order_data.get('number', '')}")
            else:
                print("WebSocket未连接，无法发送更新")
        except Exception as e:
            print(f"发送订单更新失败: {e}")
    
    def on_customer_updated(self):
        """客户数据更新处理"""
        print("客户数据已更新")
        # 同步更新文件夹设置组件的客户数据
        if hasattr(self.customer_management, 'customers_data'):
            self.folder_settings.update_customers_data(self.customer_management.customers_data)
    
    def on_task_statistics_updated(self):
        """任务统计数据更新处理"""
        # 同步更新生产管理组件的数据
        self._sync_production_data()
    
    def _sync_production_data(self):
        """同步生产管理数据"""
        if hasattr(self.task_statistics_widget, 'get_all_records'):
            records = self.task_statistics_widget.get_all_records()
            self.production_management.update_projects(records)
    
    def on_production_status_update(self, pdf_name: str, serial_number: str, new_status: str):
        """生产管理状态更新请求"""
        # 通过任务统计组件的WebSocket发送更新请求
        if hasattr(self.task_statistics_widget, 'update_order_status'):
            try:
                success = self.task_statistics_widget.update_order_status(serial_number, new_status)
                if success:
                    print(f"✅ 生产管理状态更新: {pdf_name} - {serial_number} -> {new_status}")
                else:
                    print(f"⚠️ 生产管理状态更新失败: {pdf_name} - {serial_number} -> {new_status}")
            except Exception as e:
                print(f"❌ 生产管理状态更新异常: {pdf_name} - {serial_number} -> {new_status}, 错误: {e}")
        else:
            print(f"⚠️ 无法更新状态: {serial_number} -> {new_status} (task_statistics_widget 没有 update_order_status 方法)")
    
    def on_websocket_message(self, message: dict):
        """处理WebSocket消息"""
        # 转发给客户管理组件
        self.customer_management.handle_websocket_message(message)
        
        # 如果是客户数据相关的消息，同步更新文件夹设置组件
        msg_type = message.get('type')
        if msg_type in ['customers_received', 'customer_created', 'customer_updated', 'customer_deleted']:
            if hasattr(self.customer_management, 'customers_data'):
                self.folder_settings.update_customers_data(self.customer_management.customers_data)
        
    def on_file_changed(self, event):
        """文件变化处理（保留用于兼容性）"""
        print(f"检测到文件变化: {event.path} - {event.event_type}")
        
        # 当文件变化时，自动重新解析订单
        # 延迟执行以避免频繁解析
        if hasattr(self, '_parse_timer'):
            self._parse_timer.stop()
        
        from PyQt6.QtCore import QTimer
        self._parse_timer = QTimer()
        self._parse_timer.setSingleShot(True)
        self._parse_timer.timeout.connect(self._auto_parse_orders)
        self._parse_timer.start(1000)  # 1秒后执行解析
        
    def on_folder_connected(self, path, connected):
        """文件夹连接状态变化"""
        status = "已连接" if connected else "连接失败"
        self.setWindowTitle(f"下单管理 - {path}: {status}")
    
    def _check_express_pending_alarm(self):
        """检查是否有快递客户的新挂版"""
        try:
            # 检查订单表格中的数据
            if not hasattr(self.order_table, 'orders_data') or not self.order_table.orders_data:
                self.has_express_pending = False
                self._update_alarm_status()
                return
            
            # 遍历订单，检查是否有开头是1或3，且"挂"按钮是红色的订单
            for row, order_data in enumerate(self.order_table.orders_data):
                order_number = order_data.get('number', '')
                
                # 检查订单编号开头是否是1或3或4
                if not order_number or order_number[0] not in ['1', '3', '4']:
                    continue
                
                # 检查"挂"按钮的状态（第7列，固态4、未刻版5、未确认6、挂7、已做8）
                if row < self.order_table.table.rowCount():
                    pending_btn = self.order_table.table.cellWidget(row, 7)
                    if pending_btn:
                        style = pending_btn.styleSheet()
                        # 检查是否为红色背景
                        if "#f44336" in style or "background-color: #f44336" in style:
                            # 找到符合条件的订单
                            self.has_express_pending = True
                            self._update_alarm_status()
                            print(f"🚨 检测到快递客户新挂版: {order_number} - {order_data.get('customer', '')}")
                            return
            
            # 没有找到符合条件的订单
            self.has_express_pending = False
            self._update_alarm_status()
            
        except Exception as e:
            print(f"❌ 检查快递客户挂版失败: {e}")
            import traceback
            traceback.print_exc()
    
    def _update_alarm_status(self):
        """更新告警状态显示"""
        if self.has_express_pending:
            # 开启闪烁
            if not self.alarm_blink_timer.isActive():
                self.alarm_blink_timer.start(500)  # 每500ms闪烁一次
        else:
            # 停止闪烁，清空显示
            self.alarm_blink_timer.stop()
            self.alarm_status_label.setText("")
            self.alarm_status_label.setStyleSheet("""
                QLabel {
                    padding: 0px;
                    background-color: transparent;
                    border: none;
                    color: #888;
                    font-size: 24px;
                }
            """)
    
    def _blink_alarm(self):
        """闪烁告警标签"""
        if self.alarm_visible:
            # 显示告警信息（红色）
            self.alarm_status_label.setText("快递客户有新的挂版，请及时处理")
            self.alarm_status_label.setStyleSheet("""
                QLabel {
                    padding: 0px;
                    background-color: transparent;
                    border: none;
                    color: #f44336;
                    font-weight: bold;
                    font-size: 24px;
                }
            """)
        else:
            # 隐藏（透明）
            self.alarm_status_label.setText("快递客户有新的挂版，请及时处理")
            self.alarm_status_label.setStyleSheet("""
                QLabel {
                    padding: 0px;
                    background-color: transparent;
                    border: none;
                    color: transparent;
                    font-weight: bold;
                    font-size: 24px;
                }
            """)
        
        self.alarm_visible = not self.alarm_visible
